// -------------- select2 配置  ----------//
var FormSamples = function () {


    return {
        //main function to initiate the module
        init: function () {

            // use select2 dropdown instead of chosen as select2 works fine with bootstrap on responsive layouts.
            $('.select2_category').select2({
                placeholder: "Select an option",
                allowClear: false
            });
            // 不能清空选项

            $('.select2_sample1').select2({
                placeholder: "Select a State",
                allowClear: true
            });

            $(".select2_sample2").select2({
                placeholder: "Type to select an option",
                allowClear: true,
                minimumInputLength: 1,
                query: function (query) {
                    var data = {
                        results: []
                    }, i, j, s;
                    for (i = 1; i < 5; i++) {
                        s = "";
                        for (j = 0; j < i; j++) {
                            s = s + query.term;
                        }
                        data.results.push({
                            id: query.term + i,
                            text: s
                        });
                    }
                    query.callback(data);
                }
            });

            $(".select2_sample3").select2({
                tags: ["red", "green", "blue", "yellow", "pink"]
            });

        }

    };

}();


// --------------- vue 实例 --------------//
var _Global_Data = {

    "selected_machine_id" : '',      //选中的机器的id

    "selected_machine_aisles" : [],  //被选中的机器的货道信息

    "machine_infos" : [],  //本地存储的机器信息数组

    "all_products" : {},     //全部商品

    "opto" : {}, //眼镜参数

    "colors" : [],           //产品颜色

    "current_aisle" : '',        //当前货道

    "product_type" : 'Glass',        //选中的产品的类别

    "selected_product_id" : '',     //选中的产品id

    "selected_color_id" : '',         //选中的颜色id

    "selected_rd": '',                   // 选中的球镜

    "selected_as": '',                   // 选中的柱镜

    "selected_axis": '',                   // 选中的轴位

    current_product_has_rd: false,              // 当前商品是否有rd

};

var _EMPTY = "无";
var _ERROR_IMAGE_SRC = '/at/media/image/vending/vendor-aisle-product.png';

var AisleResource = new Resource( API_LIST.AISLE_SET , Vue.http);
var ProductColorResource = new Resource( API_LIST.AISLE_PRODUCT_COLOR , Vue.http);

!function reviseAisle() {

    var vm = new Vue({

        el : "#dashboard",

        data : _Global_Data,

        created : function(){

            var self = this;

            self.initData()
                .then(function(succeed){

                    if(succeed){
                        //给select2设置初始值
                        $("#machine_select").val(self.selected_machine_id).trigger('change');
                    }

                })

        },

        computed : {

            //  商品类型判断
            productJudge : function productJudge(){

                if ( this.product_type == 'Glass' ||
                    this.product_type == 'Lens' ||
                    this.product_type == 'BeautyContactLens') {
                    return true;
                }else {
                    return false
                }
            },

            // 隐形眼镜类型
            isContactLens: function () {
                return (this.product_type === 'TransparentContactLens' || this.product_type === 'BeautyContactLens')
            },

            // 透明隐形眼镜
            isTransparentContactLens: function () {
                return this.product_type === 'TransparentContactLens';
            },

            isBeautyContactLens: function () {
                return this.product_type === 'BeautyContactLens';
            },

            // 镜片
            isLens: function () {
                return this.product_type === 'Lens';
            },

            isGlass: function () {
                return this.product_type === 'Glass';
            },

            isNursingSupply: function (){
                return this.product_type === 'NursingSupply';
            },

            hasRd: function () {
                if( this.isNursingSupply ){
                    return false;
                }else{
                    if( this.isGlass && !this.current_product_has_rd ){
                        return false;
                    }else {
                        return true;
                    }
                }
            },

            /**
             * 获取当前商品的信息。
             * @param product_id
             * @return {*}
             */
            getCurrentProductInfo: function () {
                if( this.current_aisle ){
                    var product = {};
                    var self = this;
                    var productions = this.all_products[this.product_type];
                    productions.forEach(function (item) {
                        if( item.id === Number(self.selected_product_id) ){
                            product = item;
                        }
                    });
                    return product;
                }else{
                    return {};
                }
            },

        },

        methods : {

            //点击选择机器型号
            showType : function showType( e ) {

                if( this.selected_machine_id == e.target.value ) return;

                this.selected_machine_id = e.target.value;

                if( this.selected_machine_id == '' ) return;

                this.aisleRequest(this.selected_machine_id); //切换机器型号时请求

            },
            //商品类型选择
            glassTypeSelect : function glassTypeSelect( e ) {

                if( this.product_type == e.target.value ) return;

                this.product_type = e.target.value;

                $('.product_select').val('').trigger('change');

                $('.color_select').val('').trigger('change');

            },
            //点击选择商品
            productSelect : function productSelect( e ) {

                var self = this;

                if( self.selected_product_id == e.target.value ) return;

                self.selected_product_id = e.target.value; // 保存值

                if( self.product_type == 'NursingSupply' || self.product_type == 'TransparentContactLens' ) return;

                self.getProductColor( self.selected_product_id,self.product_type )
                    .then(function(){

                        self.selected_color_id = self.colors[0].id;

                        $('.color_select').val(self.colors[0].id).trigger('change');

                    });

                if (this.product_type === 'Glass' ) { // 切换眼镜默认设置选项的第一项
                    self.selected_rd = self.opto.sph[0];
                    self.selected_as = self.opto.cyl[0];
                    self.selected_axis = self.opto.axis[0];
                    self.setOptionOfProduct(self.selected_rd, self.selected_as, self.selected_axis);
                }
            },
            //颜色选择
            colorSelect : function colorSelect( e ) {

                if( this.selected_color_id == e.target.value ) return;

                this.selected_color_id = e.target.value;

            },

            /**
             * 选择球镜的回调
             * @param {object} event
             */
            selectRd: function (event) {
                this.selected_rd = event.target.value.toString();
            },

            /**
             * 选柱镜的回调
             * @param {object} event
             */
            selectAs: function (event) {
                this.selected_as = event.target.value.toString();
            },

            /**
             * 选轴位的回调
             * @param {object} event
             */
            selectAxis: function (event) {

                this.selected_axis = event.target.value.toString();

            },

            /**
             * 图片加载错误事件
             * @param event
             */
            imageError: function (event) {
                event.target.src = _ERROR_IMAGE_SRC;
            },


            //请求货道信息的方法
            aisleRequest : function aisleRequest( id ) {

                App.blockUI('#product_single');

                var self = this;

                return AisleResource.edit(id)
                    .then(function(res){

                        if( parseInt(res.data.code) === 0 ){

                            App.unblockUI('#product_single');

                            self.selected_machine_aisles = res.data.aisles;

                            return true;

                        }else{

                            App.unblockUI('#product_single');

                            alert(res.error);

                            return false;

                        }

                    })
                    .catch(function(err){

                        console.log(err);

                        App.unblockUI('#product_single');

                        alert('请求货道信息异常，请重试！');

                    });

            },
            //点击设置货道商品的方法
            reviseProduct : function reviseProduct( id ) {

                var self = this;

                self.filterCurrentAisle(id); // 过滤货道

                self.setOptionOfProduct(self.current_aisle.rd, self.current_aisle.as, self.current_aisle.axis); // 设置select选项


                if( !self.current_aisle.typed_product_id ) {    //不存在时设置默认为眼镜

                    this.product_type = 'Glass';

                    $('.product_type_select').val(this.product_type).trigger('change');

                    $('.product_select').val('').trigger('change');

                    $('.color_select').val('').trigger('change');

                    return;

                }

                self.product_type = self.current_aisle.product_type;

                $('.product_type_select').val(self.current_aisle.product_type).trigger('change');

                self.selected_product_id = self.current_aisle.typed_product_id;

                $('.product_select').val(self.current_aisle.typed_product_id).trigger('change');

                if( self.isTransparentContactLens || self.isNursingSupply  ) return; // 透明隐形眼镜或护理商品不请求颜色数据

                // 重新获取颜色数据option
                self.getProductColor( self.current_aisle.typed_product_id, self.current_aisle.product_type )
                    .then(function(succeed){

                        if(succeed){
                            var color_id = '';
                            if( !self.current_aisle.color || self.isEmpty(self.current_aisle.color.id) ){ // 后端数据颜色为空
                                color_id = self.colors[0].id; // 默认第一项
                            }else{
                                color_id = self.current_aisle.color.id;
                            };
                            $('.color_select').val(color_id).trigger('change');
                            self.selected_color_id = color_id;
                        }
                    });

            },

            /**
             * 设置眼镜的数据, 默认设置option的第一项
             * @return {undefined}
             */
            setOptionOfProduct: function (rd, as, axis) {

                if( this.isGlass) {
                    rd = this.isEmpty(rd) ? this.opto.sph[0] : String(rd);
                    $("select.select2_rd").val(rd).trigger('change');
                    this.selected_rd = rd;

                    if (this.isContactLens) return;  // 隐形眼镜不设置以下选项

                    as = this.isEmpty(as) ? this.opto.cyl[0] : String(as);
                    $('.select2_as').val(as).trigger('change');
                    this.selected_as = as;

                    if (this.isLens) return; // 镜片眼镜不设置以下选项

                    axis = this.isEmpty(axis) ?  this.opto.axis[0] :String(axis);
                    $('.select2_axis').val(axis).trigger('change');
                    this.selected_axis =axis;
                }
            },

            /**
             * 判断是否为null
             * @param val
             * @return {boolean}
             */
            isEmpty: function (val) {
                return  (typeof val === 'object' && !val) || (val === _EMPTY);
            },

            //根据商品拿到该商品对应的所有颜色
            getProductColor : function getProductColor( id , type ) {

                var self = this;

                var params = {

                    product_id : id,

                    product_type : type

                };

                App.blockUI('#attention-form');

                return ProductColorResource.index( params )
                    .then(function(res){

                        if( parseInt(res.data.code) === 0 ){

                            self.colors = res.data.colors;

                            self.current_product_has_rd = !!res.data.has_rd;

                            App.unblockUI('#attention-form');

                            return true;

                        }else {

                            App.unblockUI('#attention-form');

                            alert(res.data.error);

                        }

                    })
                    .catch(function(err){

                        console.log(err);

                        App.unblockUI('#attention-form');

                        alert('请求颜色列表异常，请重试！');

                    })

            },

            //过滤出当前货道数据的方法
            filterCurrentAisle : function filterCurrentAisle( id ) {

                var self = this;

                self.selected_machine_aisles.forEach(function(item){

                    item.forEach(function(column){

                        if(column.aisle_id == id) {

                            self.current_aisle = column;

                        }

                    });

                });

            },

            //确认货物补充
            confirmAisle : function confirmAisle() {

                var self = this;

                var post_data = {};

                App.blockUI('#attention-form');

                var post_data = self.getUpdateParams();
                console.dir( post_data );

                AisleResource.update( self.selected_machine_id,post_data )
                            .then(function(res){

                                if( parseInt(res.data.code) === 0 ){

                                    alert('设置成功！');

                                    self.aisleRequest(self.selected_machine_id); // 成功后重新请求货道信息

                                    self.current_aisle.typed_product_id = self.selected_product_id;
                                    self.current_aisle.product_type = self.product_type;

                                    if( self.current_aisle.color ){

                                        self.current_aisle.color.id = self.selected_color_id;

                                    }else {

                                        if( self.product_type == 'Glass' ||
                                            self.product_type == 'BeautyContactLens' ||
                                            self.product_type == 'Lens' ){

                                            self.current_aisle.color = {};

                                            self.current_aisle.color.id = self.selected_color_id;

                                        }

                                    }

                                    var current_product = self.all_products[self.product_type].filter(function(item){

                                        return item.id == self.selected_product_id;

                                    })[0];

                                    self.current_aisle.img = current_product.thumb_img;

                                    $('.close').trigger('click');

                                    // 重置货道信息

                                }else {

                                    alert(res.data.error);

                                }

                                App.unblockUI('#attention-form');

                            })
                            .catch(function(err){

                                console.log(err);

                                App.unblockUI('#attention-form');

                                alert('设置货道异常，请重试！');

                            })

            },

            /**
             *  获取当前商品类型的参数
             *  @return {object}
             */
            getUpdateParams: function () {
                var params = { // 基本数据
                    'typed_product_id' : this.selected_product_id,
                    'product_type' : this.product_type,
                    'aisle_id' : this.current_aisle.aisle_id,
                };

                if( !this.isTransparentContactLens && !this.isNursingSupply ){ // 不是护理商品且不是隐形颜色设置颜色
                    params['color_id'] = this.selected_color_id;
                }

                if( this.isGlass ){ // 如果是眼镜添加轴位, 球光，柱光数据
                    if( this.hasRd ){
                        params['rd'] = this.selected_rd;
                    }
                    params['axis'] = this.selected_axis;
                    params['as'] = this.selected_as;
                }

                if(this.isLens){ // 镜片类型添加球光，柱光数据
                    params['rd'] = this.selected_rd;
                    params['as'] = this.selected_as;
                    params['axis'] = this.selected_axis;
                }

                if( this.isContactLens ){ //隐形眼镜添加球光数据
                    params['as'] = this.selected_as;
                }

                return params;
            },

            //获取数据
            initData : function initData() {

                var self = this;

                return AisleResource.create()
                    .then(function( res ){

                        var data = res.data;

                        if( parseInt(data.code) === 0 ){

                            self.all_products = data.all_products;

                            self.opto = data.opto;

                            self.machine_infos = data.vendor_machines;

                            self.selected_machine_id = data.vendor_machines[0].id;

                            self.aisleRequest(self.selected_machine_id); // 默认请求第一个

                            return true;

                        }else {

                            alert(res.data.error);

                        }

                    })
                    .catch(function( err ){

                        alert("初始化数据异常，请重试！");

                    })

            }
        }
    })

}();



